package com.easylinkin.linkappapi.security.config;

import com.easylinkin.linkappapi.security.service.LinkappUserService;
import com.easylinkin.sm.constant.LogConstant.Module;
import com.easylinkin.sm.entity.Log;
import com.easylinkin.sm.service.LogService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.session.data.redis.RedisIndexedSessionRepository;
import org.springframework.stereotype.Component;
import site.morn.framework.context.AccountContext;

/**
 * 登出成功处理
 *
 * @author TianGanLin
 * @since 1.0.0, 2019/9/12
 */
@Component
public class LinkappRestLogoutSuccessHandler implements LogoutSuccessHandler {

  @Autowired
  private LinkappUserService userService;

  @Autowired
  private LogService logService;

  @Resource
  private RedisIndexedSessionRepository sessionRepository;

  @Override
  public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
      Authentication authentication) {

    String username = null;
    if (authentication != null) {
      username = authentication.getName();
    }
    // 清空登录缓存
    if (username != null) {
      AccountContext.cacheGroup().clearKey(username);
    }
    // 记录日志
    Log log = new Log();
    log.setModuleId(Long.parseLong(Module.LOGIN));
    log.setIp(request.getRemoteAddr());
    log.setContent("用户登出");
    log.setStatus(true);
    log.setDisplay(true);
    log.setCreator(username);
    log.setModifier(username);
    logService.add(log);

    sessionRepository.deleteById(request.getRequestedSessionId());

  }
}
